package com.piper.core.aop;

import com.piper.core.exception.ServiceException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * 参数校验的aop
 */
@Aspect
@Order(510)
public class ParamValidateAop {

    //校验工具
    private ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    @Before("@annotation(com.piper.core.stereotype.ParamValidator)")
    public void doInvoke(JoinPoint joinPoint) {
        Validator validator = validatorFactory.getValidator();
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            if (arg == null) continue;
            Set<ConstraintViolation<Object>> violationSet = validator.validate(arg);
            if (violationSet == null || violationSet.isEmpty()) continue;
            for (ConstraintViolation<Object> v : violationSet) {
                throw new ServiceException(500, v.getPropertyPath() + " " + v.getMessage());
            }
        }
    }
}
